package hxy.bytecode.datastruct;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
//synchronized
//java.util.concurrent.locks.Lock
 
public class ThreadTest {
	
	private class Adder implements Runnable{
		@Override
		public void run() {
			while(true){
				//1
//				synchronized (ThreadTest.this) {
//					System.out.println("j++=" + j++);
//				}
				//2
				lock.lock();
				try{
					System.out.println("j++=" + j++);
				}finally{
					lock.unlock();
				}
			}
		}	
	}	
	
	private class Subtractor implements Runnable{
		@Override
		public void run() {
			while(true){
				//1
//				synchronized(ThreadTest.this){
//					System.out.println("j--=" + j--);
//				}
				//2
				lock.lock();
				try{
					System.out.println("j--=" + j--);
				}finally{
					lock.unlock();
				}
			}
		}		
	}
	
	private int j;
	private Lock lock = new ReentrantLock();
	
	public static void main(String[] args) {
		ThreadTest tt = new ThreadTest();
		for(int i=0; i<2; i++){
			new Thread(tt.new Adder()).start();
			new Thread(tt.new Subtractor()).start();
		}
	}
}